package com.bestcem.xm.award.util;

import com.bestcem.xm.award.entity.pojo.AwardAwardDO;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 抽奖工具类
 *
 * @author hang.li <hang.li@idiaoyan.com>
 * @version v1.0
 * @date 2021/7/15 20:24
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DrawUtil {

    public static Random random = new Random();

    /**
     * 短信模板参数正则匹配
     */
    public static final Pattern SMS_PATTERN = Pattern.compile("\\$?\\{(.*?)}");

    /**
     * 短信内容<p></p>标签正则匹配
     */
    public static final Pattern P_PATTERN = Pattern.compile("(<p.*?>)|(</p>)");

    /**
     * 生成随机兑奖码
     *
     * @param prefix 兑奖码前缀
     * @param n 随机数位数
     * @return 兑奖码
     */
    public static String generateCode(String prefix, int n) {
        return prefix + ((long) (random.nextDouble() * 9 * Math.pow(10, n - 1)) + (long) Math.pow(10, n - 1));
    }

    /**
     * 创建概率池进行抽奖
     *
     * @param awards 奖项列表
     * @return 奖项等级
     */
    public static Integer createProbabilityPool(List<AwardAwardDO.Award> awards) {
        Map<Integer, BigDecimal> propMap = new HashMap<>(16);
        for (AwardAwardDO.Award award : awards) {
            propMap.put(award.getLevel(), award.getProb());
        }
        List<Integer> levelList = new ArrayList<>(propMap.keySet());
        List<BigDecimal> propList = new ArrayList<>(propMap.values());
        BigDecimal[] propArr = new BigDecimal[propList.size()];
        for (int i = 0; i < propList.size(); i++) {
            propArr[i] = i > 0 ? propList.get(i).add(propArr[i - 1]) : propList.get(i);
        }
        double flag = random.nextDouble();
        int index = -1;
        for (int i = 0; i < propArr.length; i++) {
            if (new BigDecimal(flag).multiply(new BigDecimal(100)).compareTo(propArr[i]) < 0) {
                index = i;
                break;
            }
        }
        return index == -1 ? null : levelList.get(index);
    }

    /**
     * 短信内容html标签去除
     *
     * @param smsContent 短信内容
     * @return 短信内容
     */
    public static String smsContentHtmlLabelsRegexp(String smsContent) {
        Matcher matcher = P_PATTERN.matcher(smsContent);
        smsContent = matcher.replaceAll("");
        return smsContent;
    }
}